import java.io.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.*;
import org.math.plot.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import org.jfree.data.*;
import org.jfree.data.statistics.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;

public class ExtractRestaurantReview {
	public final static String biz_file = "C:\\Users\\Administrator\\Desktop\\research\\Yelp\\yelp_business.json";
	public final static String user_file = "C:\\Users\\Administrator\\Desktop\\research\\Yelp\\yelp_user.json";
	public final static String check_file = "C:\\Users\\Administrator\\Desktop\\research\\Yelp\\yelp_checkin.json";
	public final static String review_file = "C:\\Users\\Administrator\\Desktop\\research\\Yelp\\yelp_review.json";
	public final static String res_review_file = "C:\\Users\\Administrator\\Desktop\\research\\Yelp\\yelp_res_review.json";
	ArrayList<String> biz_list; 
	
	public ExtractRestaurantReview(){
		JSONParser myParser = new JSONParser();
		BufferedReader br = null;
		biz_list = new ArrayList();
		
		try {
			br = new BufferedReader(new FileReader(biz_file));
			String bizLine="";
			while((bizLine = br.readLine())!=null){
				Object obj = myParser.parse(bizLine);
	 
				JSONObject jsonObject = (JSONObject) obj;
				//String name = (String) jsonObject.get("name");
				
				ArrayList<String> list = (ArrayList)jsonObject.get("categories");
				// Get all restaurants in business file and save the id in the biz_list
				if(list.contains("Restaurants")) biz_list.add((String)jsonObject.get("business_id"));
			}
			br.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Restaurants #: "+biz_list.size());
			
		ArrayList<Double> lenList = new ArrayList<Double>();
				
		try {
			br = new BufferedReader(new FileReader(review_file));
			String reviewLine="";
			File file = new File(res_review_file);
			if (!file.exists()) {
				file.createNewFile();
			}
 
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			
			while((reviewLine = br.readLine())!=null){
				Object obj = myParser.parse(reviewLine);
	 
				JSONObject jsonObject = (JSONObject) obj;
				//String name = (String) jsonObject.get("name");
				
				if( biz_list.contains((String)jsonObject.get("business_id"))) {
					bw.write(reviewLine+"\n");
				}
			}
			bw.close();
		}catch(Exception e){
			
		}
	}
	
	public static void main(String[] args){
		new ExtractRestaurantReview();
	}
}
